using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;
using System.Text;

namespace BlazeApps.Library.Form
{
    [Serializable()]
    public class FormControlsDetail : Csla.BusinessBase<FormControlsDetail>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _formControlID = Guid.NewGuid();
        private int _controlType = 0;
        private string _control = string.Empty;
        private string _controlName = string.Empty;
        private bool _requiresRows = false;
        private bool _requiresColumns = false;

        [System.ComponentModel.DataObjectField(true, true)]
        public Guid FormControlID
        {
            get
            {
                CanReadProperty("FormControlID", true);
                return _formControlID;
            }
        }

        public int ControlType
        {
            get
            {
                CanReadProperty("ControlType", true);
                return _controlType;
            }
            set
            {
                CanWriteProperty("ControlType", true);
                if (!_controlType.Equals(value))
                {
                    _controlType = value;
                    PropertyHasChanged("ControlType");
                }
            }
        }

        public string Control
        {
            get
            {
                CanReadProperty("Control", true);
                return _control;
            }
            set
            {
                CanWriteProperty("Control", true);
                if (value == null)
                    value = string.Empty;
                if (!_control.Equals(value))
                {
                    _control = value;
                    PropertyHasChanged("Control");
                }
            }
        }

        public string ControlName
        {
            get
            {
                CanReadProperty("ControlName", true);
                return _controlName;
            }
            set
            {
                CanWriteProperty("ControlName", true);
                if (value == null)
                    value = string.Empty;
                if (!_controlName.Equals(value))
                {
                    _controlName = value;
                    PropertyHasChanged("ControlName");
                }
            }
        }

        public bool RequiresRows
        {
            get
            {
                CanReadProperty("RequiresRows", true);
                return _requiresRows;
            }
            set
            {
                CanWriteProperty("RequiresRows", true);
                if (!_requiresRows.Equals(value))
                {
                    _requiresRows = value;
                    PropertyHasChanged("RequiresRows");
                }
            }
        }

        public bool RequiresColumns
        {
            get
            {
                CanReadProperty("RequiresColumns", true);
                return _requiresColumns;
            }
            set
            {
                CanWriteProperty("RequiresColumns", true);
                if (!_requiresColumns.Equals(value))
                {
                    _requiresColumns = value;
                    PropertyHasChanged("RequiresColumns");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _formControlID;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // ControlType
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "ControlType");
            //
            // ControlName
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "ControlName");
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in FormControlsDetail
            //AuthorizationRules.AllowRead("FormControlID", "FormControlsDetailReadGroup");
            //AuthorizationRules.AllowRead("ControlType", "FormControlsDetailReadGroup");
            //AuthorizationRules.AllowRead("ControlName", "FormControlsDetailReadGroup");
            //AuthorizationRules.AllowRead("RequiresRows", "FormControlsDetailReadGroup");
            //AuthorizationRules.AllowRead("RequiresColumns", "FormControlsDetailReadGroup");

            //AuthorizationRules.AllowWrite("ControlType", "FormControlsDetailWriteGroup");
            //AuthorizationRules.AllowWrite("ControlName", "FormControlsDetailWriteGroup");
            //AuthorizationRules.AllowWrite("RequiresRows", "FormControlsDetailWriteGroup");
            //AuthorizationRules.AllowWrite("RequiresColumns", "FormControlsDetailWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in FormControlsDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("FormControlsDetailViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in FormControlsDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("FormControlsDetailAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in FormControlsDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("FormControlsDetailEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in FormControlsDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("FormControlsDetailDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private FormControlsDetail()
        { /* require use of factory method */
        }

        public static FormControlsDetail NewFormControlsDetail()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a FormControlsDetail");
            return DataPortal.Create<FormControlsDetail>();
        }

        public static FormControlsDetail GetFormControlsDetail(Guid formControlID)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a FormControlsDetail");
            return DataPortal.Fetch<FormControlsDetail>(new Criteria(formControlID));
        }

        public static void DeleteFormControlsDetail(Guid formControlID)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a FormControlsDetail");
            DataPortal.Delete(new Criteria(formControlID));
        }

        public override FormControlsDetail Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a FormControlsDetail");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a FormControlsDetail");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a FormControlsDetail");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid FormControlID;

            public Criteria(Guid formControlID)
            {
                this.FormControlID = formControlID;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {

            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@FormControlID", criteria.FormControlID);

            using (SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetFormControlByControlID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            _formControlID = dr.GetGuid("FormControlID");
            _controlType = dr.GetInt32("ControlType");
            _control = dr.GetString("Control");
            _controlName = dr.GetString("ControlName");
            _requiresRows = dr.GetBoolean("RequiresRows");
            _requiresColumns = dr.GetBoolean("RequiresColumns");
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert

        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertFormControl.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@ControlType", _controlType);
            DAL.AddParameter("@Control", _control);
            DAL.AddParameter("@ControlName", _controlName);
            DAL.AddParameter("@RequiresRows", _requiresRows);
            DAL.AddParameter("@RequiresColumns", _requiresColumns);
            DAL.AddParameter("@FormControlID", _formControlID);
        }
        #endregion //Data Access - Insert

        #region Data Access - Update

        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdateFormControl.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@FormControlID", _formControlID);
            DAL.AddParameter("@ControlType", _controlType);
            DAL.AddParameter("@Control", _control);
            DAL.AddParameter("@ControlName", _controlName);
            DAL.AddParameter("@RequiresRows", _requiresRows);
            DAL.AddParameter("@RequiresColumns", _requiresColumns);
        }

        private void UpdateChildren(SqlConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_formControlID));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery(Procs.DeleteFormControl.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@FormControlID", DbType.Guid, criteria.FormControlID);
        }

        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
